package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.gdpu.model.UserInfo;
import org.gdpu.service.BloodBankService;
import org.gdpu.service.UserInfoService;
import org.gdpu.vo.UserInfoVO;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * User: willson
 * Date: 13-11-7
 * Time: 上午9:28
 * To change this template use File | Settings | File Templates.
 */
@Component("login")
@Scope("prototype")
public class LoginAction extends MyActionSupport implements ModelDriven<UserInfoVO> {

    private UserInfoService userInfoService;
    private BloodBankService bloodBankService;

    private final UserInfoVO personVO = new UserInfoVO();

    private final static Logger logger = LogManager.getLogger(LoginAction.class);

    //用户登录
    @Override
    public String execute() throws Exception {

        if (personVO.getUserName() == null) return ERROR;
        UserInfo person = userInfoService.findPersonByUserName(personVO.getUserName());
        if (person == null) return ERROR;
        /*to do: when person doesn't have the purview group,
                 we should redirect a special page for him, like visitor.*/
        if (personVO.getPassword().equals(person.getPassword())) {
            if (person.getPowerGroup() == null) {
                personVO.setResultMessage("您还没有分配相应的角色,不存在任何权限!请找相关人士联系!");
                return ERROR;
            }

            if (!personVO.getPowerGroup().equals(person.getPowerGroup())) {
                personVO.setResultMessage("该用户不属于该角色！");
                return ERROR;
            }

            storePersonToSession(person);
            logger.info("user:" + person.getUserName() + ", group:"
                    + person.getPowerGroup() + " login the system.");
            //TODO:Can change
            HttpServletRequest request = ServletActionContext.getRequest();
            Object obj =  request.getSession().getAttribute("requestURI");
            if(obj != null) {
                view = obj.toString();
            }else {
                view = "/index.jsp";
            }
            personVO.setBloodBanks(bloodBankService.overdue());
            return VIEW;

        }
        personVO.setResultMessage("密码错误！");
        return ERROR;

    }
    public String look(){
        personVO.setBloodBanks(bloodBankService.overdue());
        personVO.setFlag(1);
        view="/index.jsp";
        return VIEW;
    }


    public String loginOut() throws Exception {
        HttpSession session = ServletActionContext.getRequest().getSession();
        UserInfo person = (UserInfo) session.getAttribute("person");
        if (person != null) {
            logger.info(person.getUserName() + " leave the system by security way");
            session.removeAttribute("person");
            session.invalidate();
        }
        view = "/index.jsp";
        return VIEW;
    }


    //忘记密码
    public String forget() {
        UserInfo person = userInfoService.findPersonByUserName(personVO.getUserName());
        if (person == null) {
            personVO.setResultMessage("该用户不存在！");
            return ERROR;
        }
        if (personVO.getUserName().equals(person.getUserName())) {
            personVO.setResultMessage("用户密码：" + person.getPassword());
            return SUCCESS;
        }
        personVO.setResultMessage("用户信息有误！");
        return ERROR;
    }

    @Override
    public UserInfoVO getModel() {
        return personVO;
    }

    @Resource(name = "userInfoServiceImpl")
    public void setPersonService(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    @Resource(name = "bloodBankServiceImpl")
    public void setBloodBankService(BloodBankService bloodBankService) {
        this.bloodBankService = bloodBankService;
    }

    private void storePersonToSession(UserInfo target) {
        HttpSession session = ServletActionContext.getRequest().getSession();
        UserInfo storedPerson = (UserInfo) session.getAttribute("person");
        if (storedPerson == null || !storedPerson.equals(target)) {
            session.setAttribute("person", target);
            session.setAttribute("loginKey", "success");
            session.setMaxInactiveInterval(-1);
        }
    }
}
